<?php

namespace App\Admin\Controllers\Order;

use App\Http\Controllers\Controller;
use App\Model\Cart;
use App\Model\Commodity_info;
use App\Model\Order;
use App\Model\Parent_order;
use App\Model\Trading_stream;
use App\Model\User;
use App\Model\User_address;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

/**
 * Class ApiOrderController
 * @package App\Admin\Controllers\Order
 * @User wuqin
 * @Date 2018/4/14 0014
 * @Time 13:21
 */
class ApiOrderController extends Controller
{
    use ModelForm;
    /**
     * @var Order
     */
    private $order;
    /**
     * @var Parent_order
     */
    private $parent_order;
    /**
     * @var User
     */
    private $user;
    /**
     * @var Cart
     */
    private $cart;
    /**
     * @var Trading_stream
     */
    private $trading_stream;
    /**
     * @var Commodity_info
     */
    private $commodity_info;
    /**
     * @var User_address
     */
    private $user_address;

    private $model;

    /**
     * OrderController constructor.
     * @param User_address $user_address
     * @param Order $order
     * @param Parent_order $parent_order
     * @param User $user
     * @param Cart $cart
     * @param Trading_stream $trading_stream
     * @param Commodity_info $commodity_info
     */
    function __construct(User_address $user_address, Order $order, Parent_order $parent_order, User $user, Cart $cart, Trading_stream $trading_stream, Commodity_info $commodity_info)
    {
        $this->user_address = $user_address;
        $this->order = $order;
        $this->parent_order = $parent_order;
        $this->user = $user;
        $this->cart = $cart;
        $this->trading_stream = $trading_stream;
        $this->commodity_info = $commodity_info;
//        $this = $user;
    }

    /**
     * 方法 : add_state
     * @User wuqin
     * @DateTime 2018-04-14 13:21
     * @param Request $request
     * @param Parent_order $parent_order
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_state(Request $request, Parent_order $parent_order)
    {
        $post = $request->input();
        if (empty($post))
            return return_message(1, "非法参数");

        if (empty($post["id"]))
            return return_message(1, "非法订单");

        if (empty($post["state"]))
            return return_message(1, "状态码不得为空");

        $parent_order = $parent_order->find($post["id"]);

        if (empty($parent_order) || empty($parent_order->toArray()))
            return return_message(1, "该订单不存在");

        $parent_order->state++;

        if (!$parent_order->save())
            return return_message(1, "更改状态失败");
        return return_message(0, "更改状态成功", $parent_order->toArray());
    }

    /**
     * 方法 : delete_order
     * @User wuqin
     * @DateTime 2018-04-14 13:21
     * @param Request $request
     * @param Parent_order $parent_order
     * @param Order $order
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete_order(Request $request, Parent_order $parent_order, Order $order)
    {
        $post = $request->input();
        if (empty($post))
            return return_message(1, "非法参数");

        if (empty($post["id"]))
            return return_message(1, "非法订单");

        //开启事务
        $this->trans_begin();

        $parent_order = $parent_order->find($post["id"]);

        if (empty($parent_order) || empty($parent_order->toArray())) {
            $this->trans_rollback();
            return return_message(1, "该订单不存在");
        }
        $parent_orderData = $parent_order->toArray();
        if ($parent_orderData["state"] != 6) {
            $this->trans_rollback();
            return return_message(1, "该订单未关闭不可删除");
        }

        $order = $order->getOrderByParent($parent_order->parent_order_id);

        //操作开始
        //操作开始
        foreach ($order as $key => $value) {

            $orderModel = new Order();
            $orderModel = $orderModel->deleteByPrimary($value["order_id"]);
            if (!$orderModel) {
                $this->trans_rollback();
                return return_message(1, "子订单删除失败");
            }
        }

        if (!$parent_order->delete()) {
            $this->trans_rollback();
            return return_message(1, "订单删除失败");
        }

        $this->trans_commit();
        return return_message(0, "订单删除失败");
    }

    /**
     * 方法 : close_order
     * @User wuqin
     * @DateTime 2018-04-14 13:21
     * @param Request $request
     * @param Parent_order $parent_order
     * @param Order $order
     * @return \Illuminate\Http\JsonResponse
     */
    public function close_order(Request $request, Parent_order $parent_order, Order $order)
    {
        $post = $request->input();
        if (empty($post))
            return return_message(1, "非法参数");

        if (empty($post["id"]))
            return return_message(1, "非法订单");


        //开启事务
        $this->trans_begin();

        $parent_order = $parent_order->find($post["id"]);

        if (empty($parent_order) || empty($parent_order->toArray())) {
            $this->trans_rollback();
            return return_message(1, "该订单不存在");
        }
        $parent_orderData = $parent_order->toArray();

        $this->user = $this->user->find($parent_orderData["user_id"]);
        if (empty($this->user) || empty($this->user->toArray())) {
            $this->trans_rollback();
            return return_message(1, "该用户不存在");
        }


        $order = $order->getOrderByParent($parent_order->parent_order_id);

        //操作开始
        foreach ($order as $key => $value) {

            $infoModel = new Commodity_info();
            $infoModel = $infoModel->find($value["info_id"]);

            //加库存
            $infoModel->commodity_info_number += $value["number"];
            if (!$infoModel->save()) {
                $this->trans_rollback();
                return return_message(1, "库存返还失败");
            }

        }

        if ($parent_orderData["state"] != 0) {
            //交易流水
            $type = config('bar.trading_stream.type');
            $tsData = array(
                "user_id" => $parent_orderData['user_id'],
                "change" => $parent_orderData["all_price"],
                "info" => $type[2][1],
                "type" => $type[2][0],
            );
            $this->trading_stream = $this->trading_stream->add_trading_stream($tsData);
            if (!$this->trading_stream->save()) {
                $this->trans_rollback();
                return return_message(1, "交易流水生成失败");
            }

            //返还用户余额
            $this->user->balance += (float)$parent_orderData["all_price"];
            if (!$this->user->save()) {
                $this->trans_rollback();
                return return_message(1, "用户余额返还");
            }
        }

        $parent_order->state = 6;

        if (!$parent_order->save()) {
            $this->trans_rollback();
            return return_message(1, "更改状态失败");
        }

        $this->trans_commit();
        return return_message(0, "关闭订单成功");
    }

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Parent_order::class, function (Grid $grid) {

            $grid->id('ID')->sortable();

            $grid->created_at();
            $grid->updated_at();
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Parent_order::class, function (Form $form) {

            $form->display('id', 'ID');

            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }
}
